package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.AdminCacheConstant;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private SecurityConfigProperties securityConfigProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate ;

    @Override
    public UserVo login(LoginDto loginDto) {
        //根据用户名查询用户
        User user = userMapper.selectByName(loginDto.getUsername());

        //判断用户是否为空
        if (ObjectUtil.isEmpty(user)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //判断用户是否被禁用
        if (user.getDataState().equals(SuperConstant.DATA_STATE_1)){
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        //判断密码是否正确
        if (!BCrypt.checkpw(loginDto.getPassword(), user.getPassword())){
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        //对象转换
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        //密码托敏
        userVo.setPassword("");

        //获取当前用户对应的资源列表
       List<Resource> resourceList = resourceMapper.selectListByUserId(userVo.getId());
       //取出request_path
        List<String> urlList = resourceList.stream().map(resource -> resource.getRequestPath()).collect(Collectors.toList());
        //获取白名单  公共资源
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        //合并
        urlList.addAll(publicAccessUrls);

        //根据用户生成JWT
        String jsonStr = JSONUtil.toJsonStr(userVo);
        HashMap<String, Object> claims = new HashMap<>();

        claims.put("currentUser",jsonStr);
        // 生成token
        String token = JwtUtil.createJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(), claims);

        //过期时间  秒
       int ttl = jwtTokenManagerProperties.getTtl()/1000;
        //储存到redis
        stringRedisTemplate.opsForValue().set(
                AdminCacheConstant.PUBLIC_ACCESS_URLS+userVo.getId(),
                JSONUtil.toJsonStr(urlList),
                ttl,
                TimeUnit.SECONDS
        );

        // 设置token
        userVo.setUserToken(token);

        return userVo;
    }
}
